package cn.commander.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Date;
import java.util.Properties;

/**
 * ClassName: SendEmail
 * Author: zhongyi_yang <br/>
 * Description: 发送无附件的电子邮件
 * Version: 1.0
 * Date: 2017/2/10 15:18
 */
public class SendEmail extends Authenticator {
	private static final Logger logger = LoggerFactory.getLogger(SendEmail.class);
	private String mailServerHost; // 发送邮件的服务器的IP

	private String fromE_mail = SpringPropertiesUtils.parseStr("email.from");//发送邮件的邮箱
	private String passwordToFromE_mail = SpringPropertiesUtils.parseStr("email.password.from");//发送邮件邮箱对应的邮箱密码
	private String theme = SpringPropertiesUtils.parseStr("email.theme");//邮件主题
	private String messageContent = SpringPropertiesUtils.parseStr("email.info");//邮件内容

	public SendEmail() {
	}

	public SendEmail(String fromE_mail, String passwordToE_mail) {
		this.fromE_mail = fromE_mail;
		this.passwordToFromE_mail = passwordToE_mail;
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(fromE_mail, passwordToFromE_mail);
	}

	/**
	 * 获得邮件会话属性
	 *
	 * @param fromE_mail 发送邮件的邮箱
	 * @return 返回Properties类型的对象
	 */
	public Properties getProperties(String fromE_mail) {
		Properties p = new Properties();
		if (fromE_mail.endsWith("@126.com")) {
			mailServerHost = "smtp.126.com";//适用于发送的地址为xxx@126.com
		} else if (fromE_mail.endsWith("@163.com")) {
			mailServerHost = "smtp.163.com";//适用于发送的地址为xxx@163.com
		} else {
			logger.debug("邮箱地址无效，请使用163或126的邮箱发送邮件");
		}
		p.put("mail.smtp.host", mailServerHost);
		p.put("mail.smtp.port", "25");
		p.put("mail.smtp.auth", "true");
		return p;
	}

	/**
	 * 以HTML格式发送邮件
	 *
	 * @param toE_mail 指明要将邮件发到哪个邮箱中
	 * @return 邮件发送成功返回true，否则返回false
	 */
	public boolean sendHtmlMail(String toE_mail) {
		boolean flag = false;
		String code = (int) ((Math.random() * 9 + 1) * 100000) + "";
		messageContent = messageContent.replace("{username}", toE_mail).replace("{emailCode}", code);
		fromE_mail = fromE_mail.toLowerCase();//将fromE_mail中的所有字符都转换为小写
		Properties pro = new SendEmail().getProperties(fromE_mail);
		SendEmail SendEmail = new SendEmail(fromE_mail, passwordToFromE_mail);  // 由于需要身份认证，所以则创建一个密码验证器
		Session sendMailSession = Session.getDefaultInstance(pro, SendEmail); // 根据邮件会话属性和密码验证器构造一个发送邮件的session
		try {
			Message mailMessage = new MimeMessage(sendMailSession);  // 根据session创建一个邮件消息
			Address from = new InternetAddress(fromE_mail); // 创建邮件发送者地址
			mailMessage.setFrom(from); // 设置邮件消息的发送者
			Address to = new InternetAddress(toE_mail); // 创建邮件的接收者地址
			mailMessage.setRecipient(Message.RecipientType.TO, to); // 将邮件接收者的地址设置到邮件消息中 ，Message.RecipientType.TO属性表示接收者的类型为TO
			mailMessage.setSubject(theme); // 设置邮件消息的主题 
			mailMessage.setSentDate(new Date()); // 设置邮件消息发送的时间
			Multipart mainPart = new MimeMultipart(); // MineMultipart类是一个容器类，包含MimeBodyPart类型的对象
			BodyPart html = new MimeBodyPart(); // 创建一个包含HTML内容的MimeBodyPart 
			html.setContent(messageContent, "text/html; charset=UTF-8"); // 设置发送的html内容
			mainPart.addBodyPart(html);
			mailMessage.setContent(mainPart); // 将MimeMultipart对象设置为邮件内容
			Transport.send(mailMessage); // 发送邮件 
			logger.info("HTML格式发送邮件成功");
			flag = true;
		} catch (MessagingException ex) {
			logger.debug("\n邮件发送失败\n");
			ex.printStackTrace();
//			throw new EmailException("邮件发送失败");
			flag = false;//邮件发送失败,emailExceptionHandler捕获异常,返回发送结果
		}
		return flag;
	}
}
